package com.satyam.swingvalidator.core;

import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.border.Border;

/**
 * This class handles all the details of validation and decorating the component
 *
 * @author Naveed Quadri
 */
public abstract class AbstractValidator extends InputVerifier {

    private Border originalBorder;
    private Color originalBackgroundColor;
    private String originalTooltipText;
    private ValidationItem validationItem;

    public AbstractValidator() {
    }

    public void setValidationItem(ValidationItem validationItem) {
        this.validationItem = validationItem;
        getOrigialAttributesOfComponent();
    }

    protected abstract Severity getValidationCriteria(JComponent c);

    @Override
    public boolean verify(JComponent c) {
        if (validationItem.isOptionalValidator()) {
            String strToValidate = ((JTextField) c).getText();
            if(strToValidate.trim().equals(""))
                return true;
        }

        Severity severity = getValidationCriteria(c);

        if (severity.getErrorType() == Severity.NO_ERROR) {
            c.setBackground(originalBackgroundColor);
            c.setBorder(originalBorder);
            c.setToolTipText(originalTooltipText);
            validationItem.setValidity(true);
            return true;
        } else if (severity.getErrorType() == Severity.INFO) {
            c.setBorder(new IconBorder(severity.getImageIcon(), BorderFactory.createLineBorder(severity.getColor())));
            c.setToolTipText(severity.getMessage());
            validationItem.setValidity(true);
            return true;
        } else if (severity.getErrorType() == Severity.WARNING) {
            c.setBorder(new IconBorder(severity.getImageIcon(), BorderFactory.createLineBorder(severity.getColor())));
            c.setToolTipText(severity.getMessage());
            validationItem.setValidity(true);
            return true;
        } else {
            c.setBorder(new IconBorder(severity.getImageIcon(), BorderFactory.createLineBorder(severity.getColor())));
            c.setToolTipText(severity.getMessage());
            validationItem.setValidity(false);
            return false;
        }
    }

    private void getOrigialAttributesOfComponent() {
        originalBorder = validationItem.getComponent().getBorder();
        originalBackgroundColor = validationItem.getComponent().getBackground();
        originalTooltipText = validationItem.getComponent().getToolTipText();
    }

    private void checkPerformanceTest() {
        for (ValidationItem v : validationItem.getValidationGroup().getValidationItems()) {
            System.out.print(v.getValidity() + "   ");
        }

        System.out.println("The group validity  :: " + validationItem.getGroupValidity() + "  \n");
    }

}
